package com.lzx.iteam.provider;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.lzx.iteam.EventsFragment;
import com.lzx.iteam.bean.aidl.EventReplyNewData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by shijunting on 15-5-21.
 * 事件回复数据库表
 */
public class EventsMsgDB {
    private static final String DB_NAME = "event.db";
    private SQLiteDatabase mDb;

    private static final String EVENT_ID = "event_id";
    private static final String EVENT_USER_NAME = "event_user_name";
    private static final String EVENT_USER_ID = "event_user_id";
    private static final String EVENT_UPDATE_TIME = "event_update_time";
    private static final String EVENT_CONTENT = "event_reply_content";
    private static final String EVENT_REPLY_ID = "event_reply_id";//回复的id
    private static final String EVENT_AVATAR = "event_avatar"; // 回复人头像
    private static final String EVENT_ATTACHMENT = "attachment";
    private static final String IS_READED = "is_readed";


    public EventsMsgDB(Context context) {
        mDb = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
    }


    /**
     * 创建一张表名为事件ID的事件表
     *
     * @param eventId
     */
    private void createEventTable(String eventId) {
        mDb.execSQL("CREATE table IF NOT EXISTS _" + eventId
                        + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + EVENT_REPLY_ID + " TEXT, "
                        + EVENT_USER_NAME + " TEXT, "
                        + EVENT_USER_ID + " TEXT, "
                        + EVENT_UPDATE_TIME + " TEXT, "
                        + EVENT_CONTENT + " TEXT, "
                        + EVENT_AVATAR + " TEXT, "
                        + EVENT_ATTACHMENT + " TEXT, "
                        + IS_READED + " integer ); "
        );
    }

    /**
     * 添加一条评论到某张事件表
     */
    public void insertEventReply(EventReplyNewData eventReplyData) {
        String eventId = eventReplyData.getEventId();
        createEventTable(eventId);
        int isReaded = eventReplyData.isReaded() ? 1 : 0;
        mDb.execSQL(
                "insert into _" + eventId + " (" + EVENT_USER_NAME + "," + EVENT_USER_ID + "," + EVENT_UPDATE_TIME + "," + EVENT_CONTENT + "," + EVENT_AVATAR + "," +EVENT_ATTACHMENT+","+ IS_READED
                        + ") values(?,?,?,?,?,?,?)",
                new Object[]{eventReplyData.getUserName(),
                        eventReplyData.getUserId(),
                        eventReplyData.getUpdateTime(), eventReplyData.getContent(), eventReplyData.getAvatar(), eventReplyData.getAttachments(),isReaded});
    }

    /**
     * 查询某张事件表中评论数据
     *
     * @return
     */
    public ArrayList<EventReplyNewData> findEventReplyByEventId(String eventID, int currentPage, int pageSize) {
        createEventTable(eventID);
        ArrayList<EventReplyNewData> eventReplyDatas = new ArrayList<EventReplyNewData>();
        int start = (currentPage - 1) * pageSize;
        int end = start + pageSize;
        /*String sql = "select * from _" + eventID + " order by _id  desc limit  "
                + start + " , " + end;*/
       // String sql = "select * from _" + eventID + " order by _id  desc ";
        String sql = "select * from _" + eventID + " order by event_update_time desc ";
        Cursor cursor = null;
        try {
            cursor = mDb.rawQuery(sql, null);
            while (cursor.moveToNext()) {
                EventReplyNewData eventReplyData = new EventReplyNewData();
                eventReplyData.setUserName(cursor.getString(cursor.getColumnIndex(EVENT_USER_NAME)));
                eventReplyData.setUserId(cursor.getString(cursor.getColumnIndex(EVENT_USER_ID)));
                eventReplyData.setUpdateTime(cursor.getString(cursor.getColumnIndex(EVENT_UPDATE_TIME)));
                eventReplyData.setContent(cursor.getString(cursor.getColumnIndex(EVENT_CONTENT)));
                eventReplyData.setAvatar(cursor.getString(cursor.getColumnIndex(EVENT_AVATAR)));
                eventReplyData.setIsReaded(cursor.getInt(cursor.getColumnIndex(IS_READED)) == 1);
                eventReplyData.setAttachments(cursor.getString(cursor.getColumnIndex(EVENT_ATTACHMENT)) );
                eventReplyDatas.add(eventReplyData);
            }
           // Collections.reverse(eventReplyDatas);
        } catch (Exception e) {
            Log.d("EventsMsgDB", "error___findEventReplyByEventId");
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return eventReplyDatas;
    }

    /**
     * 统计某一张事件表中的未读消息数
     *
     * @param eventId
     * @return
     */
    public int getUnReadCountOfOneEvent(String eventId) {
        Cursor cursor = null;
        int count = 0;
        try {
            createEventTable(eventId);

            String sql = "select count(*) as count from _" + eventId + " where "
                    + IS_READED + " = 0";
            cursor = mDb.rawQuery(sql, null);
            if (cursor.moveToNext())
                count = cursor.getInt(cursor.getColumnIndex("count"));

        } catch (Exception e) {
            Log.d("EventsMsgDB", "error___getUnReadCountOfOneEvent");
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return count;
    }

    /**
     * 统计所有事件表中的未读消息
     *
     * @param eventIds 元素为eventIds的list集合
     * @return
     */
    public int getUnReadCountOfAllEvent(List<String> eventIds) {
        int count = 0;
        for (String eventId : eventIds) {
            count += getUnReadCountOfOneEvent(eventId);
        }
        return count;
    }

    /**
     * 将某张事件表的所有消息置为已读状态
     *
     * @param eventID
     */
    public void updateAllMsgReaded(String eventID) {
        createEventTable(eventID);
        mDb.execSQL("update _" + eventID + " set " + IS_READED + " = 1 where " + IS_READED + " = 0 "
                , new Object[]{});
        EventsFragment.isUpDate = true;
    }

    /**
     * 删除某张事件表下的所有回复
     *
     * @param eventId
     */
    public int deleteMessagesByEventID(String eventId) {
        return mDb.delete("_" + eventId, null, null);
    }
}



